﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections.Generic;
using System.IO;
using System.Drawing;

namespace HRM
{
    public partial class frmDanhSachNgheList : DockContent
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        int department_ID = 0;
        int branch_ID = 0;

        bool cboMonthFirstLoad = true;
        MainServiceClient wcfMain;

        EmployeeClient wcfEmployee;
        RoleRightInfo listRole;
        public DataTable dtDanhSachCanhBaoNghe;

        public frmDanhSachNgheList()
        {
            InitializeComponent();
            LoadLanguage();

            wcfEmployee = Service.Employee();
            wcfMain = Service.MainService();
            BuildVoucherGrid();

            UISetting.LoadMonths(ref cboMonth);
            UISetting.LoadYears(ref cboYear);
            

            listRole = UIParamater.Quyen_CanhBaoSapSinhNhat;

            if (!listRole.Update)
            {
                this.btnViewEmloyee.Image = global::HRM.Properties.Resources.app;
                this.btnViewEmloyee.Tag = "xem";
            }

            cboYear.ComboBox.SelectedValue = (DateTime.Now.Year - 1).ToString();
            cboMonth.ComboBox.SelectedValue = DateTime.Now.Month.ToString();
            //cboYear.Text = DateTime.Now.Month.ToString();
            cboMonthFirstLoad = false;
            UISetting.LoadTreeView3(ref tvBranch);
            this.KeyPreview = true;

            //Tạm thời ẩn phần danh sách phòng ban
            //splitContainer1.Panel1Collapsed = true;
        }

        void LoadLanguage()
        {
            if (this.Tag != null)
                this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void BuildVoucherGrid()
        {
            UISetting.AddColumn(ref dgvList, "RowNumber", "STT", "C", 50, true, true);
            UISetting.AddColumn(ref dgvList, "Employee_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "Employee_FullName", UpdateUI.GetString("hovaten"), "", 200, true, true);
            UISetting.AddColumn(ref dgvList, "Employee_DateOfBirth", UpdateUI.GetString("ngaysinh"), "", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_InsBookNo", UpdateUI.GetString("sosobh"), "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_FromDate", UpdateUI.GetString("tuthang"), "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_ToDate", UpdateUI.GetString("denthang"), "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_TotalMonth", "Số tháng", "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_JobFactorPercent", "%TNN", "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "Detail_JobFactor", UpdateUI.GetString("hesothamniennghecanhbao"), "C", 110, true, true);
            UISetting.AddColumn(ref dgvList, "DLNhapDung","Nhập đúng TNN", "C", 110, true, true);
        }
        private void LoadData()
        {
            int _month = cboMonth.Visible ? Convert.ToInt32(cboMonth.Text) : 0;
            int _year = cboYear.Visible ? Convert.ToInt32(cboYear.Text) : 0;
            ptbLoading.Visible = true;
            DataSet _ds = wcfEmployee.Employee_DanhSachNgheList(out itemCount,_month,_year, branch_ID, department_ID, currPage, pageSize);
            dtDanhSachCanhBaoNghe = _ds.Tables[0];
            ptbLoading.Visible = false;
            PageIndex();

            //dgvList.Rows.Clear();

            //hiepdh: Tam thoi hien nhu theo cot lay trong DB
            dgvList.Rows.Clear();
            for (int i = 0; i < dtDanhSachCanhBaoNghe.Rows.Count; i++)
            {
                dgvList.Rows.Insert(i, 1);
                dgvList.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList.Rows[i].Cells["Employee_ID"].Value = dtDanhSachCanhBaoNghe.Rows[i]["Employee_ID"].ToString();
                dgvList.Rows[i].Cells["Employee_FullName"].Value = dtDanhSachCanhBaoNghe.Rows[i]["Employee_FullName"].ToString();
                dgvList.Rows[i].Cells["Employee_DateOfBirth"].Value = Convert.ToDateTime(dtDanhSachCanhBaoNghe.Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy");
                dgvList.Rows[i].Cells["Detail_InsBookNo"].Value = dtDanhSachCanhBaoNghe.Rows[i]["Detail_InsBookNo"].ToString();
                dgvList.Rows[i].Cells["Detail_FromDate"].Value = Convert.ToDateTime(dtDanhSachCanhBaoNghe.Rows[i]["Detail_FromDate"]).ToString("MM/yyyy");
                dgvList.Rows[i].Cells["Detail_ToDate"].Value = Convert.ToDateTime(dtDanhSachCanhBaoNghe.Rows[i]["Detail_ToDate"]).ToString("MM/yyyy");
                dgvList.Rows[i].Cells["Detail_TotalMonth"].Value = dtDanhSachCanhBaoNghe.Rows[i]["Detail_TotalMonth"].ToString();
                dgvList.Rows[i].Cells["Detail_JobFactorPercent"].Value = dtDanhSachCanhBaoNghe.Rows[i]["Detail_JobFactorPercent"].ToString();
                dgvList.Rows[i].Cells["Detail_JobFactor"].Value = Convert.ToDecimal(dtDanhSachCanhBaoNghe.Rows[i]["Detail_JobFactor"]).ToString(UIParamater.Cham3So);
                dgvList.Rows[i].Cells["DLNhapDung"].Value = Convert.ToBoolean(dtDanhSachCanhBaoNghe.Rows[i]["DLNhapDung"])  ? "Đúng" : "Sai";

                if( ! Convert.ToBoolean(dtDanhSachCanhBaoNghe.Rows[i]["DLNhapDung"]) )
                    dgvList.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
            }
            dgvList.AutoGenerateColumns = false;
            //dgvList.DataSource = _ds.Tables[0];
            

            //Tạm thời ẩn phần danh sách phòng ban
            splitContainer1.Panel1Collapsed = true;
        }
        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {
            //string _month = cboMonth.Text;
            //string _ReportText = "sinhnhattrongthang";
            //frmPreviewReport f = new frmPreviewReport("Birth day in month", new string[] { _ReportText, _month, branch_ID.ToString(), department_ID.ToString() });
            //f.Show(this);
        }

        private void btnWarning_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
            if (dgvList.Rows.Count > 0)
                btnPrint.Enabled = true;
            else
                btnPrint.Enabled = false;
        }

        private void btnViewEmloyee_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedCells.Count > 0)
            {
                int Employee_ID = Convert.ToInt32(dgvList.Rows[dgvList.SelectedCells[0].RowIndex].Cells["Employee_ID"].Value);
                //int Index = Convert.ToInt32(drgvr.Cells["RowNumber"].Value.ToString());
                
                Form f = new frmEmployeeInfo(Employee_ID, 0, 0, UIParamater.Employee_Active, listRole);
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    LoadData();
                }
            }
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                {
                    branch_ID = 0;
                    department_ID = 0;
                }
                else
                    branch_ID = Program.intBranchID;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                currPage = 0;
                LoadData();

            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            currPage = 0;
            if(!cboMonthFirstLoad)
                LoadData();
        }

        private void frmBirthDayList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
            //hiepdh: tamj thoi gen lai
            //if (dgvList.Columns.Count > 0)
            //{
            //    //dgvList.Columns["Employee_Code"].HeaderText = UpdateUI.GetString("manhanvien");
            //    dgvList.Columns["Employee_FullName"].HeaderText = UpdateUI.GetString("hovaten");
            //    dgvList.Columns["Employee_DateOfBirth"].HeaderText = UpdateUI.GetString("ngaysinh");
            //    dgvList.Columns["Detail_InsBookNo"].HeaderText = UpdateUI.GetString("sosobh");
            //    dgvList.Columns["Detail_InsTypeCode"].HeaderText = UpdateUI.GetString("phuongan");
            //    dgvList.Columns["Detail_FromDate"].HeaderText = UpdateUI.GetString("tuthang");
            //    dgvList.Columns["Detail_ToDate"].HeaderText = UpdateUI.GetString("denthang");
            //    dgvList.Columns["Detail_TotalMonth"].HeaderText = "Số tháng";
            //    dgvList.Columns["Document_MonthYear"].HeaderText = "Kỳ phát sinh";
            //    dgvList.Columns["Detail_NewJobFactorPercent"].HeaderText = UpdateUI.GetString("phantramthamniennghe");
            //    dgvList.Columns["Detail_NewJobFactor"].HeaderText = UpdateUI.GetString("hesothamniennghecanhbao");
                
            //    //dgvList.Columns["Detail_NewOverFactor"].HeaderText = UpdateUI.GetString("hesothamnienvuotkhung");
            //}
        }

        private void frmBirthDayList_FormClosing(object sender, FormClosingEventArgs e)
        {
            wcfEmployee.Close();
            wcfMain.Close();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            btnViewEmloyee_Click(null, null);

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //Refresh
            LoadData();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            string fileName = "CanhBaoThamNienNghe.xls";
            DataTable dt = new DataTable();

            try
            {
                if (dtDanhSachCanhBaoNghe.Rows.Count > 0)
                {
                    if (dtDanhSachCanhBaoNghe.Columns.Contains("Employee_ID"))
                    {
                        dtDanhSachCanhBaoNghe.Columns["Employee_ID"].Caption = "STT";
                        dtDanhSachCanhBaoNghe.Columns["Employee_ID"].AutoIncrement = true;
                        dtDanhSachCanhBaoNghe.Columns["Employee_ID"].AutoIncrementSeed = 1;
                    }
                    //dtDanhSachCanhBaoNghe.Columns.Remove("Employee_ID");
                    dtDanhSachCanhBaoNghe.Columns["Employee_FullName"].Caption = "Họ và tên";
                    dtDanhSachCanhBaoNghe.Columns["Employee_DateOfBirth"].Caption = "Ngày sinh";
                    dtDanhSachCanhBaoNghe.Columns["Detail_InsBookNo"].Caption = "Số sổ BHXH";
                    dtDanhSachCanhBaoNghe.Columns["Detail_FromDate"].Caption = "Từ tháng";
                    dtDanhSachCanhBaoNghe.Columns["Detail_ToDate"].Caption = "Đến tháng";
                    dtDanhSachCanhBaoNghe.Columns["Detail_TotalMonth"].Caption = "Số tháng";
                    dtDanhSachCanhBaoNghe.Columns["Detail_JobFactorPercent"].Caption = "%TNN";
                    dtDanhSachCanhBaoNghe.Columns["Detail_JobFactor"].Caption = "HSPC TNN";

                    //
                    ReadExcelFile.exportDataToExcel(dtDanhSachCanhBaoNghe, Path.GetTempPath() + "\\" + fileName);
                    try
                    {
                        System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + fileName);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + fileName, "Thông báo");
                    }
                }
                else
                    Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), "Không có dữ liệu!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
            }
            catch (Exception ex)
            {
                MessageBox.Show("File " + Path.GetTempPath() + "\\" + fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
            }
        }
    }
}
